/*! jQuery v1.8.3 jquery.com | jquery.org/license */
import jQuery  from 'jquery'
var _$ = jQuery;
if (typeof JSON !== "object") {
    JSON = {};
}

(function(){
    var namespace = function() {
        var a=arguments, o=null, i, j, d;
        for (i=0; i<a.length; i=i+1) {
            d=a[i].split(".");
            o=window;
            for (j=0; j<d.length; j=j+1) {
                o[d[j]]=o[d[j]] || {};
                o=o[d[j]];
            }
        }
        return o;
    };
    if(_$ && typeof _$.extend === "function"){
        _$.extend({namespace:namespace,ns:namespace});
    }else{
        namespace(_$);
        _$.namespace = namespace;
        _$.ns = _$.namespace;
    }
    _$.extend({
        rndNum:function(n){
            var rnd="";
            for(var i=0;i<n;i++)
                rnd+=Math.floor(Math.random()*10);
            return rnd;
        }
});
})();

let third ={
    api:{}
}

var api = third.api;

api.messager = (function(){
    var me = {};
    me.observers = {};
    
    me.send = function(data,options,transfer){
        
        if(!data || !options) return;
        var w = options.targetWindow;
        var orgin = options.targetOrigin||"*";
        var transfer = options.transfer || null;
        if(!w) return;
        if(_$.isBelowIE(8,9)){
            data = JSON.stringify(data);
        }
        if(transfer) w.postMessage(data,orgin,transfer);
        else w.postMessage(data,orgin);
    };

    me.receive = function(e){
        var d = null;
        if(_$.isBelowIE(8,9)){
            d = JSON.parse(e.data);
        }
        
        for(var id in me.observers){
            var ob = me.observers[id];
            ob && ob.receive && ob.receive(d?d:e.data,e.orgin,e.source);
        }
    };

    if(window.addEventListener){
        window.addEventListener("message",me.receive,false);
    }else{
        window.attachEvent("onmessage",me.receive);
    }

    return {
        addObserver:function(ob,id){
            if(!id) id = "ob_" + _$.rndNum(5);
            me.observers[id] = ob;
        },
        removeObserver:function(id){
            delete me.observers[id];
        },
        send:me.send,
        receive:me.receive
    };
})();


api.client = (function(){
    function observer(options,adapter,transfer){
        if(!options || !adapter) throw "args : options or adapter not be seted";
        var id = "ob_"+_$.rndNum(5);
        var cf = third.api.messager;
        var me = this;
                
        me.init = function(){
            cf.addObserver(this,id);
            adapter.setData = me.send;
            me.receiveHandler = adapter.getData;
        };
        me.getId = function(){
            return id;
        };
        me.send = function(data){
            if(me.filterSubject(data) && adapter.filterSend){
                var d = adapter.filterSend(data);
                cf.send(d,options,transfer);
            }
        };
        me.receiveHandler = null;
        me.receive = function(data,orgin,source){
            if(me.filterSubject(data) && adapter.filterReceive){
                var d = adapter.filterReceive(data,orgin,source);
                me.receiveHandler && me.receiveHandler(data.subject,d);
            }
        };
        me.filterSubject = function(data){
            var subjects = adapter.getSubjects?adapter.getSubjects():null;
            if(!data || !data.subject || !subjects) return false;
            if((typeof subjects === "string" && subjects === "*")
            || (subjects instanceof Array && subjects.indexOf(data.subject) > -1)){
               return true;
            }
            return false;
        };

        
    };

    return{
        create : function(options,adapter,transfer){
            return new observer(options,adapter,transfer);
        }        
    };
})();

window.Fill = window.Fill || null;
window.Valid = window.Valid || null;
window.SaveData = window.SaveData || null;
window.Execute = window.Execute || null;
window.GetData = window.GetData || null;
window.SetData = function(ff_data){
    thridAdapter.sendData("custom_refresh_domain_success",ff_data);
};
window.SetText = function(ff_text){
    thridAdapter.sendData("custom_refresh_text_success",ff_text);
};

var thridAdapter = (function(){
    var me = {};
    me.recivSubjs = [
        "FillDomain",
        "ValidateDomain",
        "GetDomain",
        "ExecuteBusinessLogic",
        "GetFormHtml",
        "WaterMark",
        "SaveDomain"
    ];

    me.sendSubjs = [
        "custom_loaded",
        "custom_page_resize",
        "custom_fill_domain_success",
        "custom_fill_domain_error",
        "custom_validate_domain_error",
        "custom_validate_domain",
        "custom_execute_business_logic_error",
        "custom_execute_business_logic_success",
        "custom_get_domain_success",
        "custom_get_form_html_success",
        "custom_refresh_domain_success",
        "custom_refresh_text_success",
        "custom_save_domain",
        "custom_close_business_win" //这个在工作流里没找到调用的代码
    ];

    me.getSubjects = function(){
        return me.recivSubjs.concat(me.sendSubjs);
    };

    me.filterSend = function(data){
        
        return data;
    };

    me.filterReceive = function(data,orgin,source){
        
        return data;
    };

    me.getData = function(subject,data){
        if(subject == "WaterMark"){
            _$.waterMark(data.data);
            return;
        }

        if(me.methodNotExsit(subject) == false) return;
        var d = data.data;
        if(subject == "FillDomain"){
            window?.Fill(d.domain,d.contorl,d.readonly);
            me.sendData("custom_fill_domain_success",{height:_$("body").height()});
            return;
        }
        if(subject == "ValidateDomain"){
            var validResult = window?.Valid(d.domain,d.contorl,d.action);
            if (typeof (validResult) == "object") {
                var requestData = { success: true, errMsg: "" };
                if (validResult) {
                    if (!validResult.success) {
                        requestData.success = false;
                    } 
                    if (validResult.errMsg && typeof validResult.errMsg == "string") {
                        requestData.errMsg = validResult.errMsg;
                    }
                }
                me.sendData("custom_validate_domain", requestData);
            } else {
                //之前的处理逻辑
                if (validResult) {
                    me.sendData("custom_validate_domain", { success: true });
                } else {
                    me.sendData("custom_validate_domain", { success: false });
                }
            }
            return;
        }
        if(subject == "SaveDomain"){
            if(window.SaveData){
                var saveResult = window.SaveData(d.domain,d.contorl,d.action);
                if (typeof (saveResult) == "object") {
                    var requestData = { success: true, errMsg: "" };
                    if (saveResult) {
                        if (!saveResult.success) {
                            requestData.success = false;
                        } 
                        if (saveResult.errMsg && typeof saveResult.errMsg == "string") {
                            requestData.errMsg = saveResult.errMsg;
                        }
                    }
                    me.sendData("custom_save_domain", requestData);
                } else {
                    //之前的处理逻辑
                    if (saveResult) {
                        me.sendData("custom_save_domain", { success: true });
                    } else {
                        me.sendData("custom_save_domain", { success: false });
                    }
                }
            }else{
                me.sendData("custom_save_domain", { success: true});
            }
            
            return;
        }
        if(subject == "ExecuteBusinessLogic"){
            var cb = function (validResult){
                if (typeof (validResult) == "object") {
                    var requestData = { success: true, errMsg: "" };
                    if (validResult) {
                        if (!validResult.success) {
                            requestData.success = false;
                        } 
                        if (validResult.errMsg && typeof validResult.errMsg == "string") {
                            requestData.errMsg = validResult.errMsg;
                        }
                    }
                    me.sendData("custom_execute_business_logic_success", requestData);
                } else {
                    //之前的处理逻辑
                    if (validResult) {
                        me.sendData("custom_execute_business_logic_success", { success: true });
                    } else {
                        me.sendData("custom_execute_business_logic_success", { success: false });
                    }
                }
            }
            window?.Execute(d.domain,d.contorl,cb);
            return;
        }
        if(subject == "GetDomain"){
            var formData = window?.GetData();
            me.sendData("custom_get_domain_success",{data:formData});
            return;
        }
        
        if(subject == "GetFormHtml"){
            me.sendData("custom_get_form_html_success",{data:window.document.body.innerHTML});
            return;
        }
    };

    //判断必要的方法是否未被实现
    me.methodNotExsit = function(subject){
        var map = {};
        map["FillDomain"] = ["Fill","custom_fill_domain_error"];
        map["ValidateDomain"] = ["Valid","custom_validate_domain_error"];
        map["ExecuteBusinessLogic"] = ["Execute","custom_execute_business_logic_error"];
        map["GetDomain"] = ["GetData","custom_get_domain_error"];
        
        for(var key in map){
            if(key == subject){
                var method = map[key][0],sendSubj = map[key][1];
                if(!window[method]){
                    me.sendData(sendSubj,"未找到"+method+"方法");
                    return false;
                }
            }
        }
        return true;
    }

    me.setData = null;
    me.sendData = function(subject,data){
        me.setData && me.setData({
            subject:subject,
            data:data
        });
    };

    return me;

})();

_$(document).ready(function(){
    window.thridClient = api.client.create({
        targetWindow : window.parent,
        targetOrigin : "*"
    },thridAdapter,null);
    window.thridClient.init();

    window.__refreshHeight = function () {
        setTimeout(function(){
            thridAdapter.sendData("custom_page_resize",{height:_$("body").height()});
        });
    };
    window.onresize = function () {
        setTimeout(function(){
            thridAdapter.sendData("custom_page_resize",{height:_$("body").height()});
        });
    };
    thridAdapter.sendData("custom_loaded", {height:_$("body").height()});
});
